<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="NOSQL,Redis," />


<meta name="description" content="什么是 Redis？Redis是一个开源的使用 ANSI C 语言编写、遵守BSD协议、基于内存并可持久化的 K-V 非关系型数据库。 Redis 和 Memcache的区别 Redis 数据类型丰富。Redis不仅仅支持简单的数据类型，还支持list、set、sortedset、hash等数据结构。  Redis可利用虚拟内存。Redis 当物理内存用完时，可以将一些很久没用到的 value 交">
<meta name="keywords" content="NOSQL,Redis">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis学习笔记">
<meta property="og:url" content="http://blog.yunshu168.com/posts/8eda3648.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="什么是 Redis？Redis是一个开源的使用 ANSI C 语言编写、遵守BSD协议、基于内存并可持久化的 K-V 非关系型数据库。 Redis 和 Memcache的区别 Redis 数据类型丰富。Redis不仅仅支持简单的数据类型，还支持list、set、sortedset、hash等数据结构。  Redis可利用虚拟内存。Redis 当物理内存用完时，可以将一些很久没用到的 value 交">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9t4bsawylj31800qw46r.jpg">
<meta property="og:updated_time" content="2019-12-11T13:47:25.361Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Redis学习笔记">
<meta name="twitter:description" content="什么是 Redis？Redis是一个开源的使用 ANSI C 语言编写、遵守BSD协议、基于内存并可持久化的 K-V 非关系型数据库。 Redis 和 Memcache的区别 Redis 数据类型丰富。Redis不仅仅支持简单的数据类型，还支持list、set、sortedset、hash等数据结构。  Redis可利用虚拟内存。Redis 当物理内存用完时，可以将一些很久没用到的 value 交">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9t4bsawylj31800qw46r.jpg">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/8eda3648.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>Redis学习笔记 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/8eda3648.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Redis学习笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-17T07:12:08+08:00">2018-08-17</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="什么是-Redis？"><a href="#什么是-Redis？" class="headerlink" title="什么是 Redis？"></a>什么是 Redis？</h2><p>Redis是一个开源的使用 ANSI C 语言编写、遵守BSD协议、基于内存并可持久化的 K-V 非关系型数据库。</p>
<h2 id="Redis-和-Memcache的区别"><a href="#Redis-和-Memcache的区别" class="headerlink" title="Redis 和 Memcache的区别"></a>Redis 和 Memcache的区别</h2><ul>
<li><p>Redis 数据类型丰富。Redis不仅仅支持简单的数据类型，还支持list、set、sortedset、hash等数据结构。</p>
</li>
<li><p>Redis可利用虚拟内存。Redis 当物理内存用完时，可以将一些很久没用到的 value 交换到磁盘。</p>
</li>
<li><p>Redis 支持数据持久化。当 Memcache 挂掉后，数据就没了。而 Redis 可以定期将数据保存到磁盘。</p>
</li>
</ul>
<a id="more"></a>
<ul>
<li><p>Redis 支持灾难恢复。当Memcache挂掉后，数据不可恢复; 而 Redis 数据丢失后可以通过AOF 恢复。</p>
</li>
<li><p>Redis 支持数据的备份。Redis支持<code>master-slave</code>模式的数据备份。</p>
</li>
</ul>
<h2 id="Redis-数据结构"><a href="#Redis-数据结构" class="headerlink" title="Redis 数据结构"></a>Redis 数据结构</h2><ul>
<li><p>String （字符串）</p>
</li>
<li><p>List （列表）</p>
</li>
<li><p>Hash（散列）</p>
</li>
<li><p>Set （集合）</p>
</li>
<li><p>SortedSet （有序集合）</p>
</li>
<li><p>HyperLogLog</p>
</li>
</ul>
<p>Redis 各种数据类型的使用场景举例分析 <a href="https://mengkang.net/356.html" target="_blank" rel="noopener">https://mengkang.net/356.html</a></p>
<h2 id="Redis-操作命令"><a href="#Redis-操作命令" class="headerlink" title="Redis 操作命令"></a>Redis 操作命令</h2><p>参考：</p>
<ul>
<li><p>Redis 命令参考 <a href="http://redisdoc.com/index.html" target="_blank" rel="noopener">http://redisdoc.com/index.html</a> </p>
</li>
<li><p>Redis 命令速查手册<br><a href="https://raw.githubusercontent.com/huangz1990/redis-cheatsheet/master/redis-cheatsheet.pdf" target="_blank" rel="noopener">https://raw.githubusercontent.com/huangz1990/redis-cheatsheet/master/redis-cheatsheet.pdf</a></p>
</li>
</ul>
<h2 id="Redis-的一些配置-命令"><a href="#Redis-的一些配置-命令" class="headerlink" title="Redis 的一些配置/命令"></a>Redis 的一些配置/命令</h2><p>配置表示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre></td><td class="code"><pre><span class="line">==配置文件全解===</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">==基本配置</span><br><span class="line">daemonize no 是否以后台进程启动</span><br><span class="line">databases 16 创建database的数量(默认选中的是database 0)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">save 900 1    #刷新快照到硬盘中，必须满足两者要求才会触发，即900秒之后至少1个关键字发生变化。</span><br><span class="line">save 300 10  #必须是300秒之后至少10个关键字发生变化。</span><br><span class="line">save 60 10000 #必须是60秒之后至少10000个关键字发生变化。</span><br><span class="line">stop-writes-on-bgsave-error yes    #后台存储错误停止写。</span><br><span class="line">rdbcompression yes    #使用LZF压缩rdb文件。</span><br><span class="line">rdbchecksum yes    #存储和加载rdb文件时校验。</span><br><span class="line">dbfilename dump.rdb    #设置rdb文件名。</span><br><span class="line">dir ./    #设置工作目录，rdb文件会写入该目录。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">==主从配置</span><br><span class="line">slaveof &lt;masterip&gt; &lt;masterport&gt; 设为某台机器的从服务器</span><br><span class="line">masterauth &lt;master-password&gt;   连接主服务器的密码</span><br><span class="line">slave-serve-stale-data yes  # 当主从断开或正在复制中,从服务器是否应答</span><br><span class="line">slave-read-only yes #从服务器只读</span><br><span class="line">repl-ping-slave-period 10 #从ping主的时间间隔,秒为单位</span><br><span class="line">repl-timeout 60 #主从超时时间(超时认为断线了),要比period大</span><br><span class="line">slave-priority 100    #如果master不能再正常工作，那么会在多个slave中，选择优先值最小的一个slave提升为master，优先值为0表示不能提升为master。</span><br><span class="line"></span><br><span class="line">repl-disable-tcp-nodelay no #主端是否合并数据,大块发送给slave</span><br><span class="line">slave-priority 100 从服务器的优先级,当主服挂了,会自动挑slave priority最小的为主服</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">===安全</span><br><span class="line">requirepass foobared # 需要密码</span><br><span class="line">rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 #如果公共环境,可以重命名部分敏感命令 如config</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">===限制</span><br><span class="line">maxclients 10000 #最大连接数</span><br><span class="line">maxmemory &lt;bytes&gt; #最大使用内存</span><br><span class="line"></span><br><span class="line">maxmemory-policy volatile-lru #内存到极限后的处理</span><br><span class="line">volatile-lru -&gt; LRU算法删除过期key</span><br><span class="line">allkeys-lru -&gt; LRU算法删除key(不区分过不过期)</span><br><span class="line">volatile-random -&gt; 随机删除过期key</span><br><span class="line">allkeys-random -&gt; 随机删除key(不区分过不过期)</span><br><span class="line">volatile-ttl -&gt; 删除快过期的key</span><br><span class="line">noeviction -&gt; 不删除,返回错误信息</span><br><span class="line"></span><br><span class="line">#解释 LRU ttl都是近似算法,可以选N个,再比较最适宜T踢出的数据</span><br><span class="line">maxmemory-samples 3</span><br><span class="line"></span><br><span class="line">====日志模式</span><br><span class="line">appendonly no #是否仅要日志</span><br><span class="line">appendfsync no # 系统缓冲,统一写,速度快</span><br><span class="line">appendfsync always # 系统不缓冲,直接写,慢,丢失数据少</span><br><span class="line">appendfsync everysec #折衷,每秒写1次</span><br><span class="line"></span><br><span class="line">no-appendfsync-on-rewrite no #为yes,则其他线程的数据放内存里,合并写入(速度快,容易丢失的多)</span><br><span class="line">auto-AOF-rewrite-percentage 100 当前aof文件是上次重写是大N%时重写</span><br><span class="line">auto-AOF-rewrite-min-size 64mb aof重写至少要达到的大小</span><br><span class="line"></span><br><span class="line">====慢查询</span><br><span class="line">slowlog-log-slower-than 10000 #记录响应时间大于10000微秒的慢查询</span><br><span class="line">slowlog-max-len 128   # 最多记录128条</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">====服务端命令</span><br><span class="line">time  返回时间戳+微秒</span><br><span class="line">dbsize 返回key的数量</span><br><span class="line">bgrewriteaof 重写aof</span><br><span class="line">bgsave 后台开启子进程dump数据</span><br><span class="line">save 阻塞进程dump数据</span><br><span class="line">lastsave </span><br><span class="line"></span><br><span class="line">slaveof host port 做host port的从服务器(数据清空,复制新主内容)</span><br><span class="line">slaveof no one 变成主服务器(原数据不丢失,一般用于主服失败后)</span><br><span class="line"></span><br><span class="line">flushdb  清空当前数据库的所有数据</span><br><span class="line">flushall 清空所有数据库的所有数据(误用了怎么办?)</span><br><span class="line"></span><br><span class="line">shutdown [save/nosave] 关闭服务器,保存数据,修改AOF(如果设置)</span><br><span class="line"></span><br><span class="line">slowlog get 获取慢查询日志</span><br><span class="line">slowlog len 获取慢查询日志条数</span><br><span class="line">slowlog reset 清空慢查询</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">info []</span><br><span class="line"></span><br><span class="line">config get 选项(支持*通配)</span><br><span class="line">config set 选项 值</span><br><span class="line">config rewrite 把值写到配置文件</span><br><span class="line">config restart 更新info命令的信息</span><br><span class="line"></span><br><span class="line">debug object key #调试选项,看一个key的情况</span><br><span class="line">debug segfault #模拟段错误,让服务器崩溃</span><br><span class="line">object key (refcount|encoding|idletime)</span><br><span class="line">monitor #打开控制台,观察命令(调试用)</span><br><span class="line">client list #列出所有连接</span><br><span class="line">client kill #杀死某个连接  CLIENT KILL 127.0.0.1:43501</span><br><span class="line">client getname #获取连接的名称 默认nil</span><br><span class="line">client setname &quot;名称&quot; #设置连接名称,便于调试</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">====连接命令===</span><br><span class="line">auth 密码 #密码登陆(如果有密码)</span><br><span class="line">ping #测试服务器是否可用</span><br><span class="line">echo &quot;some content&quot; #测试服务器是否正常交互</span><br><span class="line">select 0/1/2... #选择数据库</span><br><span class="line">quit #退出连接</span><br></pre></td></tr></table></figure>
<h2 id="关于-Redis-的持久化"><a href="#关于-Redis-的持久化" class="headerlink" title="关于 Redis 的持久化"></a>关于 Redis 的持久化</h2><p>Redis 中有两种方法进行持久化，一种是快照，一种是Append-only。</p>
<h3 id="快照"><a href="#快照" class="headerlink" title="快照"></a>快照</h3><p>Redis 以快照的形式将数据保存到一个二进制文件中（dump.rdb，名字可更改），在配置在N秒之内，至少发生M次修改则抓快照到磁盘（配置项：save N M）。我们也可以手动执行save 或者 bgsave（异步）做快照。</p>
<p>优点：不会太影响性能</p>
<p>缺点：Redis 挂掉后，最近的数据会丢失。当业务量很大时，会丢失很多数据（丢失数据的多少取决于你 save 策略的配置）。</p>
<h3 id="Append-only"><a href="#Append-only" class="headerlink" title="Append-only"></a>Append-only</h3><p>使用 Append-only 方法（Redis 配置项：appendonly yes/no），Redis 可以每执行一个命令或者每隔1秒，都会添加到 AOF 文件中（取决于 Redis 配置项：appendfsync everysec/always/no）。当 Redis 关闭后，将会读取 AOF 文件进行“重放”以恢复到关闭时刻的数据。</p>
<p>优点：丢失数据较少</p>
<p>缺点：较影响 Redis 性能</p>
<p>我们一般将 快照 + AOF 结合起来做数据的同步。</p>
<h2 id="Redis-同步机制"><a href="#Redis-同步机制" class="headerlink" title="Redis 同步机制"></a>Redis 同步机制</h2><p>Redis 可以使用主从同步，从从同步。第一次同步时，主节点做一次 bgsave，并同时将后续修改操作记录到内存 buffer，待完成后将 rdb 文件全量同步到复制节点，复制节点接受完成后将 rdb 镜像加载到内存。加载完成后，再通知主节点将期间修改的操作记录同步到复制节点进行重放就完成了同步过程。</p>
<h2 id="Redis-事务"><a href="#Redis-事务" class="headerlink" title="Redis 事务"></a>Redis 事务</h2><p>可以将多个redis命令放在一起作为原子操作，要么全部成功，要么全部失败，这时可以使用Redis中的事务。<br>Redis 中使用<code>multi</code>开启事务，过程中执行 Redis 命令，会将Redis执行命令放到队列中，执行<code>exec</code> 命令时会将队列中的命令依次执行，如果出现语法错误（如ticket键类型为string，使用sadd操作ticket将ticket当作集合用），则会出现部分成功部分失败的情况。如果多个命令执行时有的命令没有添加到队列中，则所有的命令都不会执行。只有当命令都操作正确，都执行成功时，所有的命令才都会执行。<br>Redis 中使用 <code>discard</code> 取消事务，将命令从命令中清除。<br>Redis中使用<code>watch</code>命令实现事务操作的原子性，防止事务中命令的key被其它命令修改，导致最后的结果错误。如果发现key有其它命令修改，在执行<code>exec</code>时则会返回nil，执行失败。只有key没发生改动时，才执行成功。执行<code>exec</code>后会自动执行<code>unwatch</code>取消监视该key。可使用<code>watch</code>命令监控多个key，只要有一个key值发生变化，事务中的命令都不会执行。</p>
<p>Redis中事务的相关命令。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">#开启事务</span><br><span class="line">&gt; multi</span><br><span class="line"></span><br><span class="line">#提交事务</span><br><span class="line">&gt; exec</span><br><span class="line"></span><br><span class="line">#取消执行Redis命令</span><br><span class="line">&gt; discard</span><br><span class="line"></span><br><span class="line">#监视 key 值的变化, 如果key发生变化，事务取消</span><br><span class="line">&gt; watch key</span><br><span class="line"></span><br><span class="line">#取消监视 key 的变化</span><br><span class="line">&gt; unwatch</span><br></pre></td></tr></table></figure></p>
<p>使用 <code>watch</code>命令 示例：<br><img src="https://tva1.sinaimg.cn/large/006tNbRwgy1g9t4bsawylj31800qw46r.jpg" alt="Redis事务"></p>
<h2 id="监控工具-sentinel"><a href="#监控工具-sentinel" class="headerlink" title="监控工具 sentinel"></a>监控工具 sentinel</h2><p>Sentinel不断与master通信,获取master的slave信息.<br>监听master与slave的状态<br>如果某slave失效,直接通知master去除该slave.</p>
<h2 id="PHP-操作-Redis"><a href="#PHP-操作-Redis" class="headerlink" title="PHP 操作 Redis"></a>PHP 操作 Redis</h2><p>PHP 操作 Redis，可查看 phpredis 的 github 仓库：<a href="https://github.com/phpredis/phpredis" target="_blank" rel="noopener">https://github.com/phpredis/phpredis</a></p>
<h2 id="Python-中操作-Redis"><a href="#Python-中操作-Redis" class="headerlink" title="Python 中操作 Redis"></a>Python 中操作 Redis</h2><h2 id="Redis-客户端工具"><a href="#Redis-客户端工具" class="headerlink" title="Redis 客户端工具"></a>Redis 客户端工具</h2><h2 id="Redis的使用场景"><a href="#Redis的使用场景" class="headerlink" title="Redis的使用场景"></a>Redis的使用场景</h2><ul>
<li><p>会话缓存</p>
</li>
<li><p>热点数据缓存</p>
</li>
<li><p>队列</p>
</li>
<li><p>排行榜/计数器</p>
</li>
<li><p>发布/订阅</p>
</li>
</ul>
<h2 id="其它链接"><a href="#其它链接" class="headerlink" title="其它链接"></a>其它链接</h2><p>Redis在线测试 <a href="http://try.redis.io/" target="_blank" rel="noopener">http://try.redis.io/</a></p>
<p>天下无难试之Redis面试刁难大全 <a href="https://mp.weixin.qq.com/s/507jyNbL4xCkxyW6Xk15Xg" target="_blank" rel="noopener">https://mp.weixin.qq.com/s/507jyNbL4xCkxyW6Xk15Xg</a></p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/8eda3648.html" title="Redis学习笔记">http://blog.yunshu168.com/posts/8eda3648.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/NOSQL/" rel="tag"># NOSQL</a>
          
            <a href="/tags/Redis/" rel="tag"># Redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/62b9bc40.html" rel="next" title="一些Linux基本命令与其它相关">
                <i class="fa fa-chevron-left"></i> 一些Linux基本命令与其它相关
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/4b2504f4.html" rel="prev" title="PHP7新特性">
                PHP7新特性 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是-Redis？"><span class="nav-number">1.</span> <span class="nav-text">什么是 Redis？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-和-Memcache的区别"><span class="nav-number">2.</span> <span class="nav-text">Redis 和 Memcache的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-数据结构"><span class="nav-number">3.</span> <span class="nav-text">Redis 数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-操作命令"><span class="nav-number">4.</span> <span class="nav-text">Redis 操作命令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-的一些配置-命令"><span class="nav-number">5.</span> <span class="nav-text">Redis 的一些配置/命令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于-Redis-的持久化"><span class="nav-number">6.</span> <span class="nav-text">关于 Redis 的持久化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#快照"><span class="nav-number">6.1.</span> <span class="nav-text">快照</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Append-only"><span class="nav-number">6.2.</span> <span class="nav-text">Append-only</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-同步机制"><span class="nav-number">7.</span> <span class="nav-text">Redis 同步机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-事务"><span class="nav-number">8.</span> <span class="nav-text">Redis 事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#监控工具-sentinel"><span class="nav-number">9.</span> <span class="nav-text">监控工具 sentinel</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PHP-操作-Redis"><span class="nav-number">10.</span> <span class="nav-text">PHP 操作 Redis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-中操作-Redis"><span class="nav-number">11.</span> <span class="nav-text">Python 中操作 Redis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis-客户端工具"><span class="nav-number">12.</span> <span class="nav-text">Redis 客户端工具</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis的使用场景"><span class="nav-number">13.</span> <span class="nav-text">Redis的使用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其它链接"><span class="nav-number">14.</span> <span class="nav-text">其它链接</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
